package net.hn.hnms.biz.shipped.company.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import net.hn.hnms.biz.shipped.company.enums.MineInfo;
import net.hn.hnms.biz.shipped.company.service.CompanyService;
import net.hn.hnms.biz.shipped.mapper.StatisticMapper;
import net.hn.hnms.biz.shipped.vo.TransportStatisticVO;
import net.hn.hnms.sys.common.core.constant.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class CompanyServiceImpl  implements CompanyService {


    @Autowired
    private StatisticMapper statisticMapper;


    @Override
    public TransportStatisticVO transportForBigScreenByCompanyCodeOrMineCodeOrName(String date, String companyCode, String mineCode) {

        Map<String, String> map = new HashMap<>();
        if(companyCode!=null&&!companyCode.equals("")&&(mineCode==null||mineCode=="")){
            map = MineInfo.getNameByCompanyCodeOfMap(companyCode);
        }else{
            map = MineInfo.getNameByMineCodeAndName(companyCode,mineCode,null);
        }

        StringBuffer value = new StringBuffer();
        for(String key : map.keySet()){
            value.append(key).append(",");
            //根据矿编码汇总数据
        }
        String keywordStr = value.deleteCharAt(value.length() - 1).toString();//去掉最后一个逗号
        map.clear();


        TransportStatisticVO statisticVO = new TransportStatisticVO();
        Date now = DateUtil.offsetDay(new Date(), -1);
        if (StrUtil.isNotBlank(date)) {
            now = DateUtil.parseDate(date);
        }
        Date yearBegin = DateUtil.beginOfYear(now);
        Date yearEnd = DateUtil.endOfYear(now);


        //日销量
        statisticVO.setDay(statisticMapper.realSaleTotal(keywordStr,DateUtil.beginOfDay(now), DateUtil.endOfDay(now)).divide(Constants.TEN_THOUSAND, 2, RoundingMode.CEILING));
        //月销量
        statisticVO.setMonth(statisticMapper.realSaleTotal(keywordStr,DateUtil.beginOfMonth(now), DateUtil.endOfMonth(now)).divide(Constants.TEN_THOUSAND, 2, RoundingMode.CEILING));
        //年销量
        statisticVO.setYear(statisticMapper.realSaleTotal(keywordStr,yearBegin, yearEnd).divide(Constants.TEN_THOUSAND, 2, RoundingMode.CEILING));

        //计划年销量
        DynamicDataSourceContextHolder.push("slave");
        BigDecimal planSale = statisticMapper.planSaleTotal(keywordStr,yearBegin, yearEnd);
        DynamicDataSourceContextHolder.clear();

        statisticVO.setPercentOfYear(planSale.compareTo(BigDecimal.ZERO) > 0 ?
                statisticVO.getYear().multiply(Constants.HUNDRED).divide(planSale, 2, RoundingMode.CEILING)
                : Constants.ZERO);
        return statisticVO;
    }
}
